package com.ninong.ker.admin.conf;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.ninong.ker.common.auth.SecurityAdmin;
import com.ninong.ker.common.response.CmdResponse;
import com.ninong.ker.common.tools.Signutil;

import lombok.extern.slf4j.Slf4j;

/**
 * 鉴权
 * 
 * @author cmd
 *
 */
@Slf4j
@Component
public class CmdAdminInterceptor implements HandlerInterceptor {

	private SecurityAdmin securityAdmin;

	private FilterProperties filterProperties;

	public CmdAdminInterceptor(SecurityAdmin securityAdmin, FilterProperties filterProperties) {
		this.securityAdmin = securityAdmin;
		this.filterProperties = filterProperties;
	}

	@Override
	public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o)
			throws Exception {
		String requestRri = httpServletRequest.getRequestURI();
		// 跳过不需要验证的路径
		if (isAllowPath(requestRri)) {
			return true;
		} else {
			if (securityAdmin.getAuth()) {
				String invokeTime = httpServletRequest.getHeader("invokeTime");
				String sign = httpServletRequest.getHeader("sign");
				if (!StringUtils.isEmpty(invokeTime) && !StringUtils.isEmpty(sign)) {
					if (!Signutil.interfaceSecurityAuth(Long.valueOf(invokeTime), sign,requestRri)) {
						log.info("接口有效期失效。。。。");
						sendJsonMessage(httpServletResponse, HttpStatus.REQUEST_TIMEOUT, "接口失效");
						return false;
					}
				}else {
					log.info("接口有效期失效。。。。");
					sendJsonMessage(httpServletResponse, HttpStatus.REQUEST_TIMEOUT, "接口失效");
					return false;
				}
			}
			String token = securityAdmin.getToken(httpServletRequest);
			if (StringUtils.isEmpty(token) || !securityAdmin.validateToken(token)) {
				log.info("token is empty...");
				sendJsonMessage(httpServletResponse, HttpStatus.UNAUTHORIZED, "鉴权失败");
				return false;
			} else {
				securityAdmin.checkRenewal(token);
				return true;
			}
		}
	}

	private void sendJsonMessage(HttpServletResponse httpServletResponse, HttpStatus unauthorized, String mess)
			throws IOException {
		CmdResponse jsonObject = new CmdResponse();
		jsonObject.setCode(unauthorized.value());
		jsonObject.setMessage(mess);
		httpServletResponse.setContentType("application/json;charset=UTF-8");
		httpServletResponse.setStatus(unauthorized.value());
		// 把json数据返回给浏览器：
		final SerializerFeature[] features = { SerializerFeature.DisableCircularReferenceDetect,
				SerializerFeature.WriteDateUseDateFormat };
		PrintWriter out = httpServletResponse.getWriter();
		out.print(JSONObject.toJSONBytes(jsonObject, features));
	}

	private boolean isAllowPath(String path) {
		// 遍历白名单
		for (String allowPath : filterProperties.getAllowPaths()) {
			// 判断是否允许
			if (path.startsWith(allowPath)) {
				return true;
			}
		}
		return false;
	}

	@Override
	public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o,
			ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
			Object o, Exception e) throws Exception {

	}
}
